export class BaseMod {
  constructor () {
    this.debug = false
    this.dbfix = true
    this.tablePre = 'opendb'
    this.tableName = ''
    this.params = {}
    this._dbConnection()
  }

  _dbConnection () {
    if (!this.db) {
      this.db = uniCloud.database()
      this.dbCmd = this.db.command
      this.dbAggregate = this.dbCmd.aggregate
    }
  }

  getTableName (tab) {
    tab = tab || this.tableName
    const table = (this.dbfix && !tab.includes(this.tablePre)) ? this.tablePre + '-' + tab : tab
    if (this.debug) {
      console.log('table', table)
    }
    return table
  }

  getCollection (tab) {
    return this.db.collection(this.getTableName(tab))
  }

  async getById(tab, id) {
    const info = await this.getCollection(this.getTableName(tab)).where({_id: id}).get()
    return (info && info.data.length > 0) ? info.data[0] : []
  }

  async insert (tab, params) {
    params = params || this.params
    if (this.debug) {
      console.log('params', JSON.stringify(params))
    }
    return await this.getCollection(this.getTableName(tab)).add(params)
  }

  async update (tab, params, condition) {
    params = params || this.params
    if (this.debug) {
      console.log('params', JSON.stringify(params))
    }
    return await this.getCollection(this.getTableName(tab)).where(condition).update(params)
  }

  async delete (tab, condition) {
    if (!condition) {
      return false
    }
    return await this.getCollection(this.getTableName(tab)).where(condition).remove()
  }
}
